﻿using System;
using System.IO;
using System.Threading.Tasks;
using Caliburn.Micro;
using RatingAuthor;

namespace SamizdatSearch
{
  public class UpdateDbViewModel : PropertyChangedBase
  {
    private readonly ShellViewModel _shellViewModel;
    private readonly SiDatabase _db;

    public UpdateDbViewModel(ShellViewModel shellViewModel, SiDatabase db)
    {
      _shellViewModel = shellViewModel;
      _db = db;
    }


    public double Progress
    {
      get { return _progress; }
      set
      {
        if (_progress == value) return;
        _progress = value;
        NotifyOfPropertyChange(() => Progress);
      }
    }

    private double _progress;


    public string StatusMessage
    {
      get { return _statusMessage; }
      set
      {
        if (_statusMessage == value) return;
        _statusMessage = value;
        NotifyOfPropertyChange(() => StatusMessage);
        File.AppendAllText("update.log", StatusMessage + Environment.NewLine);
      }
    }

    private string _statusMessage;



    public Statistics LastStatistics
    {
      get { return _lastStatistics; }
      set
      {
        if (_lastStatistics == value) return;
        _lastStatistics = value;
        NotifyOfPropertyChange(() => LastStatistics);
        File.AppendAllText("update.log", LastStatistics + Environment.NewLine);
      }
    }

    private Statistics _lastStatistics;


    public void OnLoaded()
    {
      Task.Factory.StartNew(Work);
    }
    
    private void Work()
    {
      File.AppendAllText("update.log", DateTime.Now.ToLongDateString() + Environment.NewLine);
      File.AppendAllText("update.log", DateTime.Now.ToLongTimeString() + Environment.NewLine);
      var loadedPagesCounter = 0;
      StatusMessage = "Загружаем статистику комментариев:";
      LastStatistics = _db.Update(new CommentsParser(),
        (pageIndex, overalPagesCount) =>
          Progress = loadedPagesCounter++ / (double)overalPagesCount);

      loadedPagesCounter = 0;
      StatusMessage = "Загружаем статистику рейтингов:";
      LastStatistics = _db.Update(new RatingAuthorParser(),
        (pageIndex, overalPagesCount) =>
          Progress = loadedPagesCounter++ / (double)overalPagesCount);

      StatusMessage = "Сохраняем полученный результат:";
      _db.Save("База Данных СИ.bin", p => Progress = p);

      StatusMessage = "Удаляем кэш:";
      PagesCache.DeleteAll(p => Progress = p);

      _shellViewModel.DbUpdated(_db);

      File.AppendAllText("update.log", "-------------------------------" + Environment.NewLine);

    }
  }
}